#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
THN WEB SERVER

Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

This library is dual-licensed.
  + For use in commercial software, please obtain a commercial license from THN Solutions LLC.    

  + For use in free software, this library is licensed under GPL version 3. A summary of 
	GPLv3 is listed below. You should also find a copy of GPLv3 as file License_GPLv3.txt 
	included with the source-code files.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as published by
    the Free Software Foundation  of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 16-Nov-12 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.IO;

using Thn;
using Thn.Net;
using Thn.Net.Http;
using Thn.Collections;
#endregion

namespace Thn.Web
{
    /// <summary>
    /// 
    /// </summary>
#if DEBUG || TESTING
    public
#else
    internal
#endif
 class DefaultFileHandler : IHttpRequestHandler
    {
        #region Fields
        string mDefaultFilename = "";
        bool mFindRequired = true;
        #endregion

        #region Properties

        #region Is Default File Exist
        /// <summary>
        /// Checks whether a default file has been found.
        /// </summary>
        protected bool IsDefaultFileExist
        {
            get
            {
                if (mFindRequired) mDefaultFilename = FindDefaultFile();
                return !string.IsNullOrEmpty(mDefaultFilename);
            }
        }
        #endregion

        #region Acceptable Names
        private List<string> mAcceptableNames = new List<string>();
        /// <summary>
        /// Gets or sets description.
        /// </summary>
        public List<string> AcceptableNames
        {
            get { return mAcceptableNames; }
            set { mAcceptableNames = value; }
        }
        #endregion

        #region Path Translator
        protected IPathTranslator mPathTranslator;
        /// <summary>
        /// Gets or sets reference to the URI to local path translator.
        /// </summary>
        public IPathTranslator PathTranslator
        {
            get { return mPathTranslator; }
            set { mPathTranslator = value; }
        }
        #endregion

        #region File Service
        protected IFileService mFileService;
        /// <summary>
        /// Gets or sets reference to the file handling service.
        /// </summary>
        public IFileService FileService
        {
            get { return mFileService; }
            set { mFileService = value; }
        }
        #endregion

        #endregion

        #region Find Default File
        string FindDefaultFile()
        {
            string result = "";

            foreach (var item in mAcceptableNames)
            {
                string path = mPathTranslator.Translate("/" + item);
                if (mFileService.Get(path) != null)
                {//found
                    result = item;

                    Log.Debug("Found default file name of {0}", path);
                    break;
                }
            }
            return result;
        }
        #endregion

        #region Process
        /// <summary>
        /// Process an incoming request.
        /// </summary>
        /// <param name="context">The context of handling.</param>
        void IHttpRequestHandler.Process(IHttpRequestHandlingContext context)
        {
            if (context.Request.Path == "/")
            {
                #region Root path -> redirect to index file if found
                if (IsDefaultFileExist)
                {
                    HttpResponse response = new HttpResponse(HttpResponseStatus.TemporaryRedirect);
                    string newUrl = "/" + mDefaultFilename;
                    response.Headers["Location"] = newUrl;
                    response.Body.Writer.WriteLine(string.Format("I have moved to a new location: {0}", newUrl));
                    context.Response = response;
                }
                #endregion
            }
            #region Defensive tracing
            else
            {

            }
            #endregion
        }
        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor.
        /// </summary>
        public DefaultFileHandler()
        {
            mAcceptableNames.Add("index.html");
            mAcceptableNames.Add("index.htm");
            mAcceptableNames.Add("default.html");
            mAcceptableNames.Add("default.htm");
        }
        #endregion
    }
}
